import preferences from '@ohos.data.preferences';
class PreferencesUtil{
  prefMap:Map<string , preferences.Preferences> = new Map()

  async loadPreference(context, name:string){

    try {

      let pref = await preferences.getPreferences(context,name)
      this.prefMap.set(name,pref)
      console.log('testTag','加载Preferences',name,'成功')
    }catch(e){
      console.log('testTag','加载Preferences',name,'失败',JSON.stringify(e))
    }

  }

  async putPreferencesValue(name:string,key:string,value:preferences.ValueType){
    if (!this.prefMap.has(name)) {
      console.log(
        'testTag','Preferences',name,'尚未初始化'
      )
      return
    }
    try {
      let pref = this.prefMap.get(name)
      await pref.put(key,value)
      await pref.flush()
      console.log('tagTest','保存成功',name,key,value)

    }catch (e){
      console.log('testTag','存储Preferences',name,'失败',JSON.stringify(e))
    }


  }
  async getPreferencesValue(name:string,key:string,defaultValue:preferences.ValueType){
    if (!this.prefMap.has(name)) {
      console.log(
        'testTag','Preferences',name,'尚未初始化'
      )
      return
    }
    try {
      let pref = this.prefMap.get(name)
      let value = await pref.get(key,defaultValue)

      console.log('tagTest','读取成功',name,key,' : ',value)
      return  value
    }catch (e){
      console.log('testTag','读取Preferences',name,'失败',JSON.stringify(e))
    }
  }
}
const preferencesUtil = new PreferencesUtil()
export default preferencesUtil as PreferencesUtil